<?php

namespace app\index\controller;
use app\common\model\Comment;
class CommentController extends UserController{
  public function _initialize($skip_action = []){
    $skip_action = ["index"];
    parent::_initialize($skip_action);
    $this->Model = new Comment();
  }

  public function index(){
    $param = $this->request->param();
    if(isset($param["belongs_type"])){
      $belongs_type = $param["belongs_type"];
    }else{
      $belongs_type = "";
    }
    if(isset($param["belongs_id"])){
      $belongs_id = intval($param["belongs_id"]);
    }else{
      $belongs_id = 0;
    }

    if(isset($param["page"])){
      $page = intval($param["page"]);
    }else{
      $page = 1;
    }

    $comment_res = $this->Model->belongsSelect($belongs_type, $belongs_id, $page);
    // return json($comment_res);
    $this->assign("comment_res", $comment_res);
    // 这里不能用return 来返回fetch结果，否则引号和“/”会被转义
    $html = $this->fetch("ajax_list");
    echo($html);
    exit();
  }

  public function create(){
    if($this->request->isPost()){
      $data = $this->getPostData();
      $res = $this->Model->saveItem($data);

      if($res["status"]){
        $this->success($res["msg"], 'index');
      }else{
        $this->error($res["msg"]);
      }
    }else{
      // $this->error($res["msg"]);
      // return $this->fetch("form");
      echo("");
    }
  }

  public function delete(){
    if($this->request->isPost()){
      $id = $this->request->post("id");
      $res = $this->Model->delItem($id);
      if($res["status"]){
        $this->success($res["msg"]);
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $this->error("您访问的页面不存在");
    }
  }

  public function _empty($name){
    //把所有城市的操作解析到city方法
    if($this->request->isAjax()){
      $this->error("您访问的页面不存在");
    }else{
      $this->redirect("index/index");
    }
  }

  private function getPostData(){
    $data = ["status" => 1];
    $param_name = ["belongs_type", "belongs_id", "parent_id", "title", "content"];
    $param = $this->request->post();
    foreach ($param_name as $key) {
      if(isset($param[$key])){
        $val = $param[$key];
      }else{
        $val = "";
      }

      switch ($key) {
      case "belongs_id":
      case "parent_id":
        $val = intval($val);
        if($val < 0){
          $val = 0;
        }
        break;
      default:
        $val = trim($val);
      }
      $data[$key] = $val;
    }

    return $data;
  }
}
